package com.finalProject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * author: Jimmmy Smile
 * date: 2021-06-09 22:00::00
 * positioan: com.finalProject
 * e-mail:jimmysmileltl@163.com
 **/
public class housepriceTop300_Spider_and_Show extends ListActivity implements Runnable, AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {
        public final String TAG = "spiderandshow";
        AdapterOfHouseprice adapter;
        Handler handler;
        List<HousePrice> list;
        private String logDate = "";
        private final String DATE_SP_KEY = "lastRateDateStr";
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
            logDate = sp.getString(DATE_SP_KEY, "");
            Log.i("List","lastRateDateStr=" + logDate);
            Thread t = new Thread(this);
            Log.i(TAG, "onCreate: 跳转成功");
            t.start();


            handler = new Handler(Looper.myLooper()) {
                public void handleMessage(Message msg) {
                    if (msg.what == 7) {
                        Log.i(TAG, "handleMessage: 数据传输成功");
                        list = (List<HousePrice>) msg.obj;
                        adapter=new AdapterOfHouseprice(com.finalProject.housepriceTop300_Spider_and_Show.this,
                                R.layout.list_item,
                                list);

                        Log.i(TAG, "handleMessage: 任务成功，查看手机吧");
                        setListAdapter(adapter);
                        Toast.makeText(com.finalProject.housepriceTop300_Spider_and_Show.this, "resize=" + list.size(), Toast.LENGTH_SHORT);
                    }
                    super.handleMessage(msg);
                }

            };
            getListView().setOnItemClickListener(this);
            getListView().setOnItemLongClickListener(this);
        }


    public void run () {
            Log.i(TAG, "run: run方法成功运行");
            List<HousePrice> data = new ArrayList<HousePrice>();
            String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
            Log.i("run","curDateStr:" + curDateStr + " logDate:" + logDate);
            if(curDateStr.equals(logDate)) {
                //如果相等，则不从网络中获取数据
                Log.i("run", "日期相等，从数据库中获取数据");
                DBManager dbManager = new DBManager(com.finalProject.housepriceTop300_Spider_and_Show.this);

                for (HousePrice hp : dbManager.listAll()) {
                    data.add(hp);
                }

            }
            else{
                try {
                    HousePrice hp1 = new HousePrice("排名", "城市", "元/平米", "住房收入比");
                    data.add(hp1);
                    Document doc =  Jsoup.connect("https://www.gotohui.com/top/").get();
                    Log.i(TAG, "run:爬虫开始运行" );
                    Elements tbodys = doc.getElementsByTag("tbody");
                    Element tbody = tbodys.get(0);
                    Elements trs = tbody.getElementsByTag("tr");
                    for (Element tr : trs) {
                        Elements tds = tr.getElementsByTag("td");
                        for (int i = 0; i < tds.size(); i += 6) {
                            Element td0= tds.get(i);
                            Element td1 = tds.get(i+1);
                            Element td3=tds.get(i+2);
                            Element td2 = tds.get(i +5);
                            String city = td1.text();
                            String rate = td2.text();
                            String price=td3.text();
                            String order=td0.text();
                            HousePrice temp=new HousePrice(order,city,price,rate);
                            data.add(temp);
                            //  Log.i(TAG, "run: " + order + "===>>" + city+"===>>"+price+"===>>"+rate);

                        }

                    }
                    DBManager dbManager = new DBManager(com.finalProject.housepriceTop300_Spider_and_Show.this);
                    dbManager.deleteAll();
                    Log.i("db","删除所有记录");
                    dbManager.addAll(data);
                    Log.i("db","添加新记录集");
                    Log.i(TAG, "run: 数据爬取成功");
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (NetworkOnMainThreadException e) {
                    e.printStackTrace();
                }
                SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString(DATE_SP_KEY, curDateStr);
                edit.commit();
                Log.i("run","更新日期结束：" + curDateStr);
            }
            Message msg = new Message();
            msg.obj=data;
            msg.what=7;
            handler.sendMessage(msg);
        }

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i(TAG, "onItemClick: ccccccccccc");
            Object itemAtPosition = getListView().getItemAtPosition(position);
            HousePrice temp = (HousePrice) itemAtPosition;
            String city = temp.getCity();
            String rate = temp.getRate();
            String price=temp.getPrice();
            String order=temp.getOrder();
            Log.i(TAG, "run:点了一下 " + order + "===>>" + city+"===>>"+price+"===>>"+rate);
            Intent intent =new Intent(this,house_price_jisuan.class);
            intent.putExtra("city",city);
            intent.putExtra("rate",rate);
            intent.putExtra("order",order);
            intent.putExtra("price",price);
            startActivity(intent);
            Log.i(TAG, "onItemClick: 传输成功");
            this.finish();


        }
        // 长按删除
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i(TAG, "onItemLongClick: 长按position"+String.valueOf(position));
            HousePrice temp = (HousePrice) getListView().getItemAtPosition(position);
            String title=temp.getCity();
            Log.i(TAG, "onItemLongClick: "+temp.getCity());
            //删除操作
            AlertDialog.Builder dialog =new AlertDialog.Builder(this);
            dialog.setTitle("提升！");
            dialog.setMessage("确认是否删除"+title);
            dialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    list.remove(position);
                    adapter.notifyDataSetChanged();
                    Log.i(TAG, "onItemLongClick:删除成功 "+title+"   剩余："+list.size());
                }
            });
            dialog.setNegativeButton("CACEL",null);
            dialog.create().show();

            return true;//false 同时长按、短按
        }

    }


